<?php
/**
 * (jobs) 备货比例
 */
namespace App\Jobs\Stocking;

use App\Models\Product\ProductSku;
use App\Models\SsBasic\AreaClassifyEstimate;
use App\Models\SsBasic\AreaSkuEstimate;
use App\Models\Stocking\StockingSku;
use App\Models\Stocking\StockingSkuRatio;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class SkuRatio implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $ratio;

    /**
     * SkuRatio constructor.
     * @param $ratio
     */
    public function __construct($ratio)
    {
        $this->ratio = $ratio;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->ratio);
    }

    private function exeFillData($ratio){
        $aseKey = [];
        $arr = [];
        foreach ($ratio as $_ratio){
            list($areaId,$pSkuId) = explode('_',$_ratio->area_psku);
            if(!array_key_exists($pSkuId,$arr)){
                $__classifyId = ProductSku::getValueById($pSkuId,'classify_id');
                $arr[$pSkuId] = $__classifyId ?: 0;
            }
            $_classifyId = $arr[$pSkuId];
            if(!$_classifyId){
                continue;
            }
            $_key = $areaId.'_'.$_classifyId;
            if(!in_array($_key,$aseKey)){
                $aseKey[] = $_key;
            }
        }
        foreach ($aseKey as $_aseKey){
            list($areaId,$classifyId) = explode('_',$_aseKey);
            $ace = AreaClassifyEstimate::query()->where('area_id',$areaId)->where('classify_id',$classifyId)->first();
            if(!$ace) continue;

            $ss = StockingSku::query()
                ->where('area_id',$areaId)
                ->whereHas('sku',function ($query) use ($classifyId){
                    $query->where('classify_id',$classifyId);
                })
                ->get();
            foreach ($ss as $_ss){
                $apKey = $areaId.'_'.$_ss->psku_id;
                $ratio = StockingSkuRatio::getRatio($apKey);
                $ase = AreaSkuEstimate::query()->firstOrNew(['area_psku' => $apKey]);
                for($i = 0;$i < AreaSkuEstimate::ESTIMATE_NUM;$i++){
                    $num = $ace->{'estimate_num'.$i} ?? 0; //赋值
                    $estimateNum = intval(round($num * $ratio));
                    $_ss->{'estimate_num'.$i} = $estimateNum;
                    $ase->{'estimate_num'.$i} = $estimateNum;
                }
                $_ss->save();
                $ase->save();
                $_ss->over_stock = StockingSku::getOverStock($_ss);
                $_ss->over_stock_value = StockingSku::getOverStockValue($_ss->over_stock,$_ss->unit_price);
                $_ss->save();
            }
        }
    }
}
